package yunjiao.javatutorials.guava.concurrent.event;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * 异步回调处理
 *
 * @author yangyunjiao
 */
public class EventProcessorAsyncExample {
    public static void main(String[] args) throws InterruptedException {
        EventProcessor processor = new EventProcessor();

        // 发送请求并设置回调
        ListenableFuture<String> future = processor.sendRequest("REQ-002", "处理订单");

        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("异步回调成功: " + result);
                System.out.println("剩余待处理请求: " + processor.getPendingRequestCount());
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("异步回调失败: " + throwable.getMessage());
                System.out.println("剩余待处理请求: " + processor.getPendingRequestCount());
            }
        }, MoreExecutors.directExecutor());

        // 模拟延迟响应
        new Thread(() -> {
            try {
                Thread.sleep(1500);
                processor.handleResponse("REQ-002", "订单处理完成: ORDER-12345");
            } catch (InterruptedException e) {
                processor.handleError("REQ-002", "处理超时");
            }
        }).start();

        // 等待异步处理完成
        Thread.sleep(3000);
    }
}
